<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            var candy = function (ratings) {
                let candyVec = new Array(ratings.length).fill(1)
                //从左向右遍历，右孩子比左孩子大就+1
                for (let i = 1; i < candyVec.length; i++) {
                    if (ratings[i] > ratings[i - 1]) {
                        candyVec[i] = candyVec[i - 1] + 1
                    }
                }
                //注意，不能从左向右遍历，  rating  1 2 2 5 4 3 2
                //                     第一次遍历: 1 2 1 2 1 1 1
                //如果从左向右的话，你咋判断5这个应该是最大的，还得回头
                //从右向左遍历，左孩子如果比右孩子大，那么就找出之前的值和右孩子+1的最大值
                for (let i = candyVec.length - 2; i >= 0; i--) {
                    if (ratings[i] > ratings[i + 1]) {
                        candyVec[i] = Math.max(candyVec[i], candyVec[i + 1] + 1)
                    }
                }
                return candyVec.reduce((pre, item) => {
                    return (pre += item)
                })
            }
        </script>
    </body>
</html>
